package com.zmhz.user;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eova.common.Easy;
import com.eova.common.utils.EncryptUtil;
import com.eova.common.utils.xx;
import com.eova.common.utils.time.DateUtil;
import com.eova.model.MetaObject;
import com.eova.service.sm;
import com.eova.template.common.util.TemplateUtil;
import com.jfinal.core.Controller;
import com.jfinal.ext.kit.DateKit;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

/**
 * 
 * 项目名称：中国种苗互助平台 类名称：FrontUserController 类描述：前台客户Controller 创建人：Liu Haibin
 * 创建时间：2017年11月28日 上午10:38:04
 */
public class FrontUserController extends Controller {

	/**
	 * 前端用户注册
	 */
	public void reg() {
		String objectCode = "pt_ob_frontusers";
		final MetaObject object = sm.meta.getMeta(objectCode);
		String json = HttpKit.readData(getRequest());
		JSONObject record = JSON.parseObject(json);
		String phone = record.getString("phone");
		String pwd = record.getString("pwd");
		Integer usertype = record.getInteger("usertype");
		Easy easy = new Easy();
		easy.setSuccess(false);
		try {
			if (xx.isEmpty(phone)) {
				easy.setMsg("请输先入手机号！");
			} else if (!isChinaPhoneLegal(phone)) {
				easy.setMsg("您输入的手机号码格式不对，请检查！");
			} else if (xx.isEmpty(pwd)) {
				easy.setMsg("请输先入密码！");
			} else if (pwd.length() < 6) {
				easy.setMsg("请输6位以上密码！");
			} else {
				String sql = "select count(*) from frontusers where phone = ?";
				// Db.use(ac.object.getDs()).queryInt(sql, str2);
				int count = Db.queryInt(sql, phone);
				if (count > 0) {
					// renderJson(new Easy("该手机号"+phone+"已注册，请更换其它手机号，或联系客服！"));
					easy.setMsg("该手机号" + phone + "已注册，请更换其它手机号，或联系客服！");
				} else {
					// Frontusers user = new Frontusers();
					Record record1 = new Record();
					record1.set("phone", phone);
					record1.set("pwd", EncryptUtil.getSM32(pwd));
					record1.set("usertype", usertype);
					String token = EncryptUtil.getSM32(phone);
					record1.set("token", token);
					String now = DateKit.toStr(new Date(), DateKit.timeStampPattern);
					record1.set("regtime", now);// 注册时间
					record1.set("lasttime", now);// 上次登录时间
					record1.set("logintime", now);// 本次登录时间
					record1.set("userstatus", 0);// 用户状态：注册用户
					record1.set("errornum", 0);// 登录

					Db.use(object.getDs()).save("frontusers", record1);

					easy.setMsg("注册成功！");
					easy.setSuccess(true);
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("token", token);
					map.put("usertype", usertype);
					map.put("userstatus", 0);
					easy.setData(map);

				}

			}
		} catch (Exception e) {
			easy.setMsg("注册异常:" + TemplateUtil.buildException(e));
		} finally {
			renderJson(easy);
		}

	}

	/**
	 * 前端用户登录
	 *
	 */
	public void login() {
		String objectCode = "pt_ob_frontusers";
		final MetaObject object = sm.meta.getMeta(objectCode);

		String json = HttpKit.readData(getRequest());
		JSONObject record = JSON.parseObject(json);
		// JSONObject record = (JSONObject) job.get("record");
		// JSONObject user = (JSONObject) job.get("user");
		String phone = record.getString("phone");
		// json = null;
		String user = "";
		Easy easy = new Easy();
		easy.setSuccess(false);
		try {
			if (xx.isEmpty(phone)) {
				// json = JsonKit.toJson(new Easy("请输先入手机号！"));
				easy.setMsg("请输先入手机号！");
			} else if (!isChinaPhoneLegal(phone)) {
				// json = JsonKit.toJson(new Easy("您输入的手机号码格式不对，请检查！"));
				easy.setMsg("您输入的手机号码格式不对，请检查！");
			} else {// 手机号输入正确
				String pwd = record.getString("pwd");
				if (xx.isEmpty(pwd)) {
					// json = JsonKit.toJson(new Easy("请输先入密码！"));
					easy.setMsg("请输先入密码！");
				} else if (pwd.length() < 6) {
					// json = JsonKit.toJson(new Easy("请输6位以上密码！"));
					easy.setMsg("请输6位以上密码！");
				} else {

					String sql = "select pwd,token,usertype,userstatus,logintime,errornum from frontusers where phone= ?";
					Record fuser = Db.use(object.getDs()).findFirst(sql, phone);
					if (xx.isEmpty(fuser)) {
						// json = JsonKit.toJson(new Easy("您输入的手机号不存在！"));
						easy.setMsg("您输入的手机号不存在！");
					} else {
						String token = fuser.getStr("token");
						pwd = EncryptUtil.getSM32(pwd);
						if (!pwd.equals(fuser.getStr("pwd"))) {// 密码错误
							// json = JsonKit.toJson(new Easy("您输入的密码不正确！"));
							easy.setMsg("您输入的密码不正确！");
							// 更新错误次数
							Integer errornum = fuser.getInt("errornum") + 1;

							sql = "update frontusers set errornum = ? where token = ?";
							Db.use(object.getDs()).update(sql, errornum, token);
							if (errornum >= 5)
								// json = JsonKit.toJson(new Easy("您密码的错误次数超过5次请明天再试，或找回密码"));
								easy.setMsg("您密码的错误次数超过5次请明天再试，或找回密码");
						} else {// 成功登录
							// json = JsonKit.toJson(new Easy());
							easy.setMsg("登录成功！");
							easy.setSuccess(true);
							Map<String, Object> map = new HashMap<String, Object>();
							map.put("token", token);
							map.put("usertype", fuser.getInt("usertype"));
							map.put("userstatus", fuser.getInt("userstatus"));
							easy.setData(map);
							/*
							 * user = "\"token\":\"" + token + "\",\"usertype\":" + fuser.getStr("usertype")
							 * + ",\"userstatus\":" + fuser.getStr("userstatus");
							 */
							// 更新本次登录时间、上次登录时间及将密码错误次数置0
							String logintime = fuser.getStr("logintime");
							String now = DateKit.toStr(new Date(), DateKit.timeStampPattern);
							logintime = xx.isEmpty(logintime) ? now : logintime;
							sql = "update frontusers set logintime = ?,lasttime = ?,errornum = 0 where token = ?";

							Db.use(object.getDs()).update(sql, now, logintime, token);

						}
					}

				}
			}
		} catch (Exception e) {
			// json = JsonKit.toJson(new Easy("登录异常:" + TemplateUtil.buildException(e)));
			easy.setMsg("登录异常:" + TemplateUtil.buildException(e));
		} finally {
			// System.out.println(System.getProperty("java.version")+"**************============");
			/*
			 * if(user.equals("")) user = "\"token\":null,\"usertype\":0,\"userstatus\":0";
			 * json = "{\"record\":" + json + ",\"user\":{"+user+"}}";
			 */
			/**
			 * Map<String,Object> map = (Map<String,Object>)JSON.toJSON(easy);
			map.put("success", "true");
			renderJson(map);
			 */
			renderJson(easy);
		}

	}

	/**
	 * 前端用户修改密码
	 */
	public void rePwd() {
		String objectCode = "pt_ob_frontusers";
		final MetaObject object = sm.meta.getMeta(objectCode);

		String json = HttpKit.readData(getRequest());
		JSONObject record = JSON.parseObject(json);
		// JSONObject record = (JSONObject) job.get("record");
		// JSONObject user = (JSONObject) job.get("user");
		String pwd = record.getString("pwd");
		Easy easy = new Easy();
		easy.setSuccess(false);
		try {

			if (xx.isEmpty(pwd)) {
				easy.setMsg("旧密码不能为空！");
			} else if (pwd.length() < 6) {
				easy.setMsg("旧密码少于6位！");
			} else {// 旧密码格式正确
				String newpwd = record.getString("newpwd");
				if (xx.isEmpty(newpwd)) {
					easy.setMsg("新密码不能为空！");
				} else if (newpwd.length() < 6) {
					easy.setMsg("新密码少于6位！");
				} else {// 新密码格式正确
					String rnewpwd = record.getString("rnewpwd");
					if (xx.isEmpty(rnewpwd)) {
						easy.setMsg("新重复密码不能为空！");
					} else if (rnewpwd.length() < 6) {
						easy.setMsg("新重复密码少于6位！");
					} else if (!rnewpwd.equals(newpwd)) {
						easy.setMsg("新密码与新重复密码不一致！");
					} else {// 新重复密码格式正确
						String sql = "select * from frontusers where token = ?";
						String token = record.getString("token");
						Record fusers = Db.use(object.getDs()).findFirst(sql, token);
						pwd = EncryptUtil.getSM32(pwd);
						if (!pwd.equals(fusers.getStr("pwd"))) {
							easy.setMsg("旧密码输入错误！");
						} else {// 更新密码
							pwd = EncryptUtil.getSM32(newpwd);
							sql = "update frontusers set pwd = ? where token = ?";
							Db.use(object.getDs()).update(sql, pwd, token);
							
							easy.setMsg("修改密码成功！");
							easy.setSuccess(true);
							

						}
					}
				}
			}
		} catch (Exception e) {
			easy.setMsg("修改密码异常:" + TemplateUtil.buildException(e));
		}finally {
			renderJson(easy);
		}
		
	}

	/**
	 * 更换手机号
	 */
	public void updatePhone() {
		String objectCode = "pt_ob_frontusers";
		final MetaObject object = sm.meta.getMeta(objectCode);

		String json = HttpKit.readData(getRequest());
		JSONObject record = JSON.parseObject(json);
		//JSONObject record = (JSONObject) job.get("record");
		//JSONObject user = (JSONObject) job.get("user");
		String phone = record.getString("phone");
		Easy easy = new Easy();
		easy.setSuccess(false);
		try {
		if (xx.isEmpty(phone)) {
			easy.setMsg("请输先入新手机号！");
		} else if (!isChinaPhoneLegal(phone)) {
			easy.setMsg("您输入的新手机号码格式不对，请检查！");
		} else {// 输入正确
			String token = record.getString("token");
			String sql = "select token from frontusers where phone = ? and token != ?";
			Record re = Db.use(object.getDs()).findFirst(sql, phone, token);
			if (!xx.isEmpty(re)) {
				easy.setMsg("其它用户正在使用该手机号！");
			} else {
				sql = "update frontusers set phone = ? where token = ?";
				Db.use(object.getDs()).update(sql, phone, token);
				easy.setMsg("更换手机号成功！");
				easy.setSuccess(true);
			}

		}
		} catch (Exception e) {
			easy.setMsg("更换手机号异常:" + TemplateUtil.buildException(e));
		}finally {
			renderJson(easy);
		}
		
	}

	
	/**
	 * 
	 */
	public void userMsg() {
		String objectCode = "pt_ob_frontusers";
		final MetaObject object = sm.meta.getMeta(objectCode);
		
		String json = HttpKit.readData(getRequest());
		/*System.out.println("--------");
		System.out.println(json);
		System.out.println("========");*/
		JSONObject record = JSON.parseObject(json);
		String token = record.getString("token");
		String sql = "select phone,userstatus from frontusers where token = ?";
		Record re = Db.use(object.getDs()).findFirst(sql, token);
		if(re.getInt("userstatus")==0) {
			re.set("msg", "请完善会员信息！");
			re.set("name", re.getStr("phone"));
			re.remove("phone");
			re.remove("userstatus");
		
			renderJson(re);
		}else {
		
			sql = "select frontusers.regtime regtime,frontusers.userstatus userstatus,users_info.gender gender,users_info.name name from (frontusers join users_info )" + 
					"where frontusers.id= users_info.userid and token = ?";
			re = Db.use(object.getDs()).findFirst(sql, token);
			
			Integer userstatus = re.getInt("userstatus");
			String msg = "";
			Boolean flag = true;
			if(userstatus==0) {
				long regtime = 180-DateUtil.getTodayIntevalDays(re.getDate("regtime").toString());
				if(regtime>0) {
					msg = "剩余免费试用期："+regtime+"天";
				}else {
					msg = "您的免费试用天数已用完";
					flag = false;
				}
			}else if(userstatus==1) {
				msg = "您已经是正式会员";
			}else {
				msg = "您的正式会员已到期";
				flag = false;
			}
			String name = re.getStr("name");
			Integer gender = re.getInt("gender");
			String ge = "";
			if(!xx.isEmpty(gender)) {
				
				if(gender==1) {
					ge = "女士";
				}else {
					ge = "先生";
				}
			}
			re.set("msg", msg);
			re.set("name", name+ge);
			//re.set("flag", flag);
			re.remove("regtime");
			re.remove("gender");
			re.remove("userstatus");
			renderJson(re);
		}
	}
	/**
	 * 添加密保
	 */
	public void userSecret() {
		String objectCode = "pt_front_ob_zmsecret";
		final MetaObject object = sm.meta.getMeta(objectCode);
		String json = HttpKit.readData(getRequest());
		JSONObject record = JSON.parseObject(json);
		String answer = record.getString("answer");
		Easy easy = new Easy();
		easy.setSuccess(false);
		if(null == record) {
			easy.setMsg("密保答案不能为空！");
		}else if(answer.length()<6){
			easy.setMsg("密保答案不能少于3个汉字或6个英文数字！");
		}else {
			
			String token = record.getString("token");
			String sql = "select id userid from frontusers where token = ?";
			Record re = Db.use(object.getDs()).findFirst(sql, token);
			/*Integer userid = re.getInt("userid");
			sql = "insert into zm_secret(question,answer,userid) value(?,?,?)";*/
			re.set("question", record.getInteger("question"));
			re.set("answer", answer);
			Boolean flag = Db.use(object.getDs()).save("zm_secret", re);
			if(flag) {
				easy.setMsg("密保设置成功！");
				easy.setSuccess(true);
			}else {
				easy.setMsg("保存密保失败！");
			}
			
		}
		renderJson(easy);
		
		
	}
	
	/**
	 * 找回密码（暂时不用）
	 */
	public void repwd() {
		String objectCode = "pt_front_ob_zmsecret";
		final MetaObject object = sm.meta.getMeta(objectCode);
		String json = HttpKit.readData(getRequest());
		JSONObject record = JSON.parseObject(json);
		String answer = record.getString("answer");
		Easy easy = new Easy();
		easy.setSuccess(false);
		if(null == record) {
			easy.setMsg("密保答案不能为空！");
		}else if(answer.length()<6){
			easy.setMsg("密保答案不能少于3个汉字或6个英文数字！");
		}else {
			String token = record.getString("token");
			String sql = "select id userid from frontusers where token = ?";
			Record re = Db.use(object.getDs()).findFirst(sql, token);
		}
	}
	/**
	 * 发布信息前收集用户默认信息
	 * 个人用户从会员表中取数据
	 * 企业用户从企业表中取数据
	 */
	public void supplyMsg() {
		String objectCode = "pt_front_ob_zmsecret";
		final MetaObject object = sm.meta.getMeta(objectCode);
		String json = HttpKit.readData(getRequest());
		JSONObject record = JSON.parseObject(json);
		String token = record.getString("token");
		//Integer userstatus = record.getInteger("userstatus");
		Integer usertype = record.getInteger("usertype");
		String sql = "";
		Record re = null;
		//0=个人用户,1=企业用户 
		if(usertype ==0) {
			sql = "select users_info.userid userid,frontusers.phone phone,a1.name province,a2.name city," + 
					" a3.name region,users_info.address address,users_info.name name "+ 
					" ,users_info.province provincecode,users_info.city citycode,users_info.region regioncode " + 
					" from (frontusers join users_info join area2 as a1 join area2 as a2 join area2 as a3) " + 
					" where frontusers.id=users_info.userid  and users_info.province = a1.zipcode and users_info.city=a2.zipcode  and users_info.region=a3.zipcode and frontusers.token =?";
			re = Db.use(object.getDs()).findFirst(sql, token);
		}else {
			sql = "select users_info.userid userid,frontusers.phone phone,a1.name province,a2.name city, " + 
					" a3.name region,corporate_info.address address,users_info.name name " + 
					" ,corporate_info.province provincecode,corporate_info.city citycode,corporate_info.region regioncode " + 
					" from (frontusers join users_info join corporate_info join area2 as a1 join area2 as a2 join area2 as a3) " + 
					" where frontusers.id=users_info.userid and frontusers.id=corporate_info.userid and corporate_info.province = a1.zipcode and corporate_info.city=a2.zipcode  and corporate_info.region=a3.zipcode  and frontusers.token =?";
			re = Db.use(object.getDs()).findFirst(sql, token);
		}
		if(xx.isEmpty(re)) {
			renderJson(new Easy("该用户未添加信息"));
		}else {
			renderJson(re);
		}
	}
	
	
	
	/**
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(DateUtil.getTodayIntevalDays("2018-1-29"));
	}
	/**
	 * 验证手机号格式是否正确
	 * 
	 * @param str
	 * @return
	 * @throws PatternSyntaxException
	 */
	public boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
		String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(str);
		return m.matches();
	}

}
